﻿#include "chatwindow.h"
#include "ui_chatwindow.h"
#include <QDate>
#include <QResizeEvent>
#include <QVBoxLayout>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QStringDecoder>

#include "bubble.h"
#include "bubblelist.h"

#include <QIcon>
#include <QGroupBox>
#include <QSpacerItem>
#include "Business/inputhandler.h"
#include <QFileDialog>
#include <ThreadPool/threadpool.h>

ChatWindow::ChatWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::ChatWindow)
{
    ui->setupUi(this);

    QVBoxLayout* layout = new QVBoxLayout();
    BtnSend = new QPushButton (this);
    textEdit = new QPlainTextEdit(this);
    bubbleList = new BubbleList(this);

    BtnSendPic = new QPushButton(this);
    BtnSendPic->setIcon(QIcon(":/icon/program/uploadPicture.svg"));

    textEdit->setMaximumHeight(150);

    bubbleList->setResizeMode(QListWidget::Adjust);
    bubbleList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    BtnSend->setText("发送");

    layout->addWidget(bubbleList);
    layout->addWidget(BtnSendPic);
    layout->addWidget(textEdit);

    QHBoxLayout* btnLayout = new QHBoxLayout(this);
    btnLayout->addStretch(1);
    btnLayout->addWidget(BtnSend);

    layout->addLayout(btnLayout);
    ui->centralwidget->setLayout(layout);

    QIcon icon(":/icon/program/comments.svg");

    this->setWindowIcon(icon);

    QObject::connect(BtnSend, &QPushButton::clicked, this, &ChatWindow::on_BtnSend_clicked);
    QObject::connect(BtnSendPic, &QPushButton::clicked, this, &ChatWindow::on_BtnSendPic_clicked);
}

ChatWindow::~ChatWindow()
{
    delete ui;
}

void ChatWindow::setWindow(const QString &account, bool isUser)
{
    this->account = account;
    setWindowTitle(account);

    UserChatWindow = isUser;
}

void ChatWindow::newChat(int avatar, const QString &text, int messageType, const QString& time)
{
    Bubble* bubble = new Bubble(this);

    if (messageType == 1) {
        if (time.isEmpty()) {
            bubble->setContent(avatar, text, QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"), width());
        } else {
            bubble->setContent(avatar, text, time, width());
        }
    } else {
        // 检查图片是否存在，如果不存在，则向服务器请求图片
        QString picPath = "./picture/" + text;
        QJsonObject in, out;
        in["FileName"] = text;
        in["FileType"] = 2;

        InputHandler::getInstance()["ChatWindow::newChat"](in, out);

        if (time.isEmpty()) {
            bubble->setPicture(avatar, picPath, QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"), width());
        } else {
            bubble->setPicture(avatar, picPath, time, width());
        }
    }


    QListWidgetItem* newListItem = new QListWidgetItem();

    newListItem->setSizeHint(bubble->sizeHint());

    bubbleList->addItem(newListItem);
    bubbleList->setItemWidget(newListItem, bubble);
}

void ChatWindow::newPicture(int avatar, const QString &picPath, const QString &time)
{
    Bubble* bubble = new Bubble(this);
    if (time.isEmpty()) {
        bubble->setPicture(avatar, picPath, QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"), width());
    } else {
        bubble->setPicture(avatar, picPath, time, width());
    }

    QListWidgetItem* newListItem = new QListWidgetItem();

    newListItem->setSizeHint(bubble->sizeHint());

    bubbleList->addItem(newListItem);
    bubbleList->setItemWidget(newListItem, bubble);
}

void ChatWindow::resizeEvent(QResizeEvent *event)
{
    //bubbleList->resize(QSize(event->size().width(), event->size().height() - textEdit->height() - BtnSend->height()));
    bubbleList->resizeEvent(event);
    textEdit->resize(QSize(event->size().width(), textEdit->height()));
}

void ChatWindow::on_BtnSend_clicked()
{
    qDebug() << "send message button clicked";
    InputHandler& handler = InputHandler::getInstance();

    QJsonObject in, out;

    QString message = textEdit->toPlainText();

    if (message.isEmpty())
        return;

    in["TargetAccount"] = account;
    in["Message"] = message;
    in["sendToUser"] = UserChatWindow;
    // 1：聊天文字，2：聊天图片
    in["MessageType"] = 1;

    handler["ChatWindow::on_BtnSend_clicked"](in, out);
}

void ChatWindow::on_BtnSendPic_clicked() {
    QString filePath = QFileDialog::getOpenFileName(this,
                                                    "请选择要上传的文件",
                                                    QDir::currentPath(),
                                                    "所有文件(*.jpg; *.png; *gif)");


    QFileInfo info(filePath);

    if (info.fileName().isEmpty()) {
        return ;
    }

    QJsonObject in, out;
    in["FileSize"] = info.size();
    in["FilePath"] = filePath;

    in["TargetAccount"] = account;
    in["sendToUser"] = UserChatWindow;

    // use another thread to transmit file
    InputHandler& handler = InputHandler::getInstance();

    ThreadPool& pool = ThreadPool::getInstance();
    pool.commit([&](QJsonObject& in, QJsonObject& out){
        handler["ChatWindow::on_BtnSendPic_clicked"](in, out);
    }, in, out);
}
